var express = require('express');
var musr = require('./users');
var fs = require('fs');
var router = express.Router();
const multer = require('multer');
var createError = require('http-errors');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, __dirname + "/uploads");
  }
});

var upload = multer({ storage: storage });

router.get('/dlcur', function (req, res, next) {
  if (musr.isLogined(req)) {
    res.download(__dirname + "/netdisk/newest_repair_data.db");
  } else {
    next(createError(403));
  }
});

router.get('/', function (req, res, next) {
  if (musr.isAdmin(req)) {
    next();
  } else if (musr.isLogined(req)) {
    res.render("netdisk/index2", { "user": musr.getUser(req) })
  } else {
    next(createError(403));
  }
});

router.post('/', function (req, res, next) {//admin only
  if (musr.isAdmin(req)) {
    next();
  } else {
    res.send({ "success": false, "err": "not_logined" });
  }
});

router.post('/upload', upload.single('upload_single'), function (req, res, next) {
  if (req.query.path === undefined || req.query.path === null || req.query.path === '') {
    res.send({ "success": false, "err": "BLANK_PATH" });
    return;
  }
  var file = req.file;
  fs.copyFileSync(file.path, `${__dirname}/netdisk/newest_repair_data.db`);
  fs.renameSync(file.path, `${__dirname}/netdisk/storage/${req.query.path}/${new Date().Format("yyyy-MM-dd_hh-mm-ss")}.db`);
  res.send({ "success": true, "err": "" });
});

router.post('/rename', function (req, res, next) {
  var path = req.query.path, newp = req.query.new;
  if (path === undefined || path === "" || newp === undefined || newp === "") {
    res.send({ "success": false });
  } else {
    try {
      fs.renameSync(__dirname + "/netdisk/storage/" + path, __dirname + "/netdisk/storage/" + newp);
      res.send({ "success": true });
    } catch {
      res.send({ "success": false });
    }
  }
});

router.post('/del', function (req, res, next) {
  var path = req.query.path;
  var fullpath = "";
  if (path === undefined || path === "") {
    res.send({ "success": false });
  } else {
    fullpath = __dirname + "/netdisk/storage/" + path;
    try {
      if (fs.statSync(fullpath).isFile()) {
        fs.rmSync(fullpath);
      } else {
        fs.rmdirSync(fullpath, { recusive: true, force: true });
      }
      res.send({ "success": true });
    } catch {
      res.send({ "success": false });
    }
  }
});

router.get('/', function (req, res, next) {
  var path = req.query.path, raw = req.query.raw;
  if (path === undefined || path === "") {
    res.redirect("/netdisk?path=.")
    return;
  }
  //Check Path
  var xpath = path, t;
  while (xpath.endsWith('/') && xpath.length > 1) xpath = xpath.substring(0, xpath.length - 2);
  t = xpath.replace("//", "/");
  while (xpath != t) { xpath = t; t = xpath.replace("//", "/"); }
  if (path != xpath) { res.redirect("/netdisk?path=" + xpath); return; }
  //Do
  var fullpath = __dirname + "/netdisk/storage/" + path;
  fullpath.replace("//", "/");
  var stat = fs.statSync(fullpath);
  if (stat.isFile()) {
    res.set({
      "Content-type": "application/octet-stream",
      "Content-Disposition": "attachment;filename=" + encodeURI(fullpath.substring(fullpath.lastIndexOf('/') + 1)),
      "Content-Length": fs.statSync(fullpath).size
    });
    fReadStream = fs.createReadStream(fullpath);
    fReadStream.on("data", (chunk) => res.write(chunk, "binary"));
    fReadStream.on("end", function () {
      res.end();
    });
    return;
  }
  fs.readdir(fullpath, (err, files) => {
    if (files === undefined) { res.send("Invalid path!"); return; }
    var detailed_files = [];
    files.forEach(f => {
      statsObj = fs.statSync(fullpath + "/" + f);
      statsObj["atime"] = getTimeStr(statsObj["atime"]);
      statsObj["mtime"] = getTimeStr(statsObj["mtime"]);
      statsObj["ctime"] = getTimeStr(statsObj["ctime"]);
      statsObj["name"] = f;
      detailed_files.push(statsObj);
    });
    res.render('netdisk/index', { "user": musr.getUser(req), "files": detailed_files, "path": path });
  });
});

router.use((req, res, next) => {
  if (musr.isAdmin(req)) {
    next();
  } else {
    res.send({ "success": false, "err": "NOT_ADMIN" });
  }
});

Date.prototype.Format = function (fmt) { //author: meizz 
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "h+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

function getTimeStr(time) {
  return time.Format("yyyy-MM-dd hh:mm:ss");
}

module.exports = router;
